//
//  SelectVipViewController.m
//  fitnessmanage
//
//  Created by 众拳科技 on 2017/10/31.
//  Copyright © 2017年 zongquankeji. All rights reserved.
//

#import "SelectVipViewController.h"
#import "SearchView.h"
#import "ChineseString.h"
#import "SelectVipTableViewCell.h"
#import "AddVenueVipViewController.h"

@interface SelectVipViewController ()<UITableViewDataSource,UITableViewDelegate>{
    
    NSString *selectStr;
    
    int startIndex;
    
    int pageSize;
}

@property(nonatomic,weak)UITableView *tableView;

@property(nonatomic,strong) NSMutableArray *indexArray;

@property(nonatomic,strong) NSMutableArray *letterResultArr;

@property (nonatomic, strong) UILabel *sectionTitleView;

@property (nonatomic, strong) NSMutableArray *stringsToSort;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) NSMutableDictionary *dataDict;

@property (nonatomic, strong) NSTimer *timer;

//选中会员的数组
@property (nonatomic, strong) NSMutableArray *selectArray;

@end

@implementation SelectVipViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"添加会员";
    
    if (self.titleStr) {
        
        self.title = self.titleStr;
    }
    
    self.view.backgroundColor = CSColorFromRGB(0xf0f0f0);
    
    self.indexArray = [ChineseString IndexArray:self.stringsToSort];
    
    self.letterResultArr = [ChineseString LetterSortArray:self.stringsToSort];
    
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnClick)];
    
    [rightButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:CSBlackColor,NSFontAttributeName:MidFont} forState:UIControlStateNormal];
    [rightButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:CSBlackColor,NSFontAttributeName:MidFont} forState:UIControlStateHighlighted];
    
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    
    //默认字母排序
    selectStr = @"characterSort";
    
    [self createSubView];
    
}

-(void)createSubView{
    
    UIButton *addBtn = [[UIButton alloc] init];
    [addBtn addTarget:self action:@selector(addVipMember)];
    [addBtn setImage:@"card_icon_add"];
    [self.view addSubview:addBtn];
    [addBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).offset(15);
        make.right.mas_equalTo(self.view).offset(-10);
        make.width.height.mas_equalTo(25);
    }];
    
    SearchView *searchView = [SearchView searchBar];
    searchView.backgroundColor = CSWhiteColor;
    searchView.placeholder = @"会员姓名、手机号、会员卡号";
    [self.view addSubview:searchView];
    [searchView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(addBtn);
        make.left.mas_equalTo(self.view).offset(10);
        make.height.mas_equalTo(40);
        make.right.mas_equalTo(addBtn.mas_left).offset(-10);
    }];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.estimatedRowHeight = 200;
    [tableView registerClass:[SelectVipTableViewCell class] forCellReuseIdentifier:@"SelectVipTableViewCell"];
    tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    tableView.sectionIndexColor = CSColorFromRGB(0x0a0a0a);//修改右边索引字体的颜色
    tableView.sectionIndexTrackingBackgroundColor = CSClearColor;//修改右边索引点击颜色
    tableView.backgroundColor = CSClearColor;
    MyTableHead *mj_head = [MyTableHead headerWithRefreshingTarget:self refreshingAction:@selector(loadStartData)];
    tableView.mj_header = mj_head;
    //tableView.mj_footer = footer;
    [tableView.mj_header beginRefreshing];
    [self.view addSubview:tableView];
    [tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(searchView.mas_bottom).offset(15);
        
        make.left.width.bottom.mas_equalTo(self.view);
    }];
    self.tableView = tableView;
}

#pragma mark 下拉
-(void)loadStartData{
    
    startIndex = 1;
    
    pageSize = 20;
    
    [self loadData];
}

#pragma mark 上拉
-(void)loadMoreData{
    
    startIndex = startIndex + 1;
    
    [self loadData];
}

-(void)loadData{
    
    //Get_MemberList
    
    [MBProgressHUD showMessage:@"加载中..." toView:self.view];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    VenueModel *venue = [VenueModel venue];
    
//    [params setObject:venue.venueId forKey:@"ShopID"];
//    
//    [params setObject:[NSString stringWithFormat:@"%d",startIndex] forKey:@"page"];
//    
//    [params setObject:[NSString stringWithFormat:@"%d",pageSize] forKey:@"rows"];
    
    [HTTPTool GET:Get_MemberList parameters:params
     
          success:^(id responseObject){
              
              [MBProgressHUD hideHUDForView:self.view];
              
              if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                  
                  NSMutableArray *resultArray = [responseObject objectForKey:@"rows"];
                  
                  if (resultArray.count > 0) {
                      
                      [self.tableView.mj_header endRefreshing];
                      
                      [self.tableView.mj_footer endRefreshing];
                  }
                  else{
                      
                      [self.tableView.mj_header endRefreshing];
                      
                      [self.tableView.mj_footer endRefreshingWithNoMoreData];
                  }
                  
                  if (startIndex == 1) {
                      
                      self.dataArray = [NSMutableArray arrayWithArray:resultArray];
                      
                      [self.stringsToSort removeAllObjects];
                      
                      [self.dataDict removeAllObjects];
                      
                      for (NSDictionary *dict in self.dataArray) {
                          
                          //后面取数据要用到ID，但是ID不影响排序
                          [self.stringsToSort addObject:[NSString stringWithFormat:@"%@\\%@",[dict objectForKey:@"Name"],[dict objectForKey:@"ID"]]];
                      }
                  }
                  else{
                      
                      [self.dataArray addObjectsFromArray:resultArray];
                      
                      for (NSDictionary *dict in resultArray) {
                          
                          //后面取数据要用到ID，但是ID不影响排序
                          [self.stringsToSort addObject:[NSString stringWithFormat:@"%@\\%@",[dict objectForKey:@"Name"],[dict objectForKey:@"ID"]]];
                      }
                  }
                  
                  self.indexArray = [ChineseString IndexArray:self.stringsToSort];
                  //
                  self.letterResultArr = [ChineseString LetterSortArray:self.stringsToSort];
                  //
                  
                  NSArray *memberIdArray = [[NSArray alloc] init];
                  
                  if (self.selectVipIdStr) {
                      
                      memberIdArray = [self.selectVipIdStr componentsSeparatedByString:@","];
                  }
                  NSMutableArray *newProArray = [[NSMutableArray alloc] init];
                  for (NSString *str in memberIdArray) {
                      if ([str isEmptyString]) {
                          continue;
                      }
                      [newProArray addObject:str];
                  }
                  
                  for (NSDictionary *dict in self.dataArray) {
                      
                      NSString *key = [NSString stringWithFormat:@"%@",[dict objectForKey:@"ID"]];
                      
                      [self.dataDict setObject:dict forKey:key];
                      
                      VenueVipModel *venueVipModel = [VenueVipModel mj_objectWithKeyValues:dict];
                      
                      NSString *memberId = venueVipModel.MemberID;
                      
                      if ([newProArray containsObject:memberId]) {
                          
                           [self.selectArray addObject:venueVipModel];
                      }
                  }
                  
                  
                  
                  [self.tableView reloadData];
              }
              
          }
     
          failure:^(NSError *error){
              
              [MBProgressHUD hideHUDForView:self.view];
          }];
}

#pragma mark - UITableViewDataSource

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if ([selectStr isEqualToString:@"characterSort"]) {
        
        return self.indexArray;
    }
    else{
        
        return nil;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    if ([selectStr isEqualToString:@"characterSort"]) {
        
        NSString *key = [self.indexArray objectAtIndex:section];
        
        return key;
    }
    else{
        
        return nil;
    }
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ([selectStr isEqualToString:@"characterSort"]) {
        
        return [self.indexArray count];
    }
    else{
        
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([selectStr isEqualToString:@"characterSort"]) {
        
        return [[self.letterResultArr objectAtIndex:section] count];
    }
    else{
        
        return self.stringsToSort.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SelectVipTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SelectVipTableViewCell"];
    
   
    
    NSString *name = [[self.letterResultArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    
    NSString *ID = [[name componentsSeparatedByString:@"\\"] lastObject];
    
    NSDictionary *dict = [self.dataDict objectForKey:ID];
    
    VenueVipModel *venueVipModel = [VenueVipModel mj_objectWithKeyValues:dict];
    
    cell.nameLabel.text = venueVipModel.Name;
    
    cell.venueVipModel = venueVipModel;
    
    if (self.selectVipIdStr) {
        
        NSArray *memberIdArray = [self.selectVipIdStr componentsSeparatedByString:@","];
        NSMutableArray *newProArray = [[NSMutableArray alloc] init];
        for (NSString *str in memberIdArray) {
            if ([str isEmptyString]) {
                continue;
            }
            [newProArray addObject:str];
        }
        
        if ([newProArray containsObject:venueVipModel.MemberID]) {
            
            cell.selectBtn.selected = YES;
        }
        else{
     
            cell.selectBtn.selected = NO;
        }
    }
    else{
        
        cell.selectBtn.selected = NO;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    if ([selectStr isEqualToString:@"characterSort"]) {
        
        [self showSectionTitle:title];
        
    }
    
    return index;
}

#pragma mark UITableViewDelegate

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if ([selectStr isEqualToString:@"characterSort"]) {
        
        return 30;
    }
    else{
        
        return 0.00001;
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.00001;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    UITableViewHeaderFooterView *head = (UITableViewHeaderFooterView *)view;
    head.backgroundColor = CSColorFromRGB(0xf8f8f8);
    [head.textLabel setTextColor:CSColorFromRGB(0x000000)];
    head.textLabel.font = BigFont;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
   
    SelectVipTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    cell.selectBtn.selected = !cell.selectBtn.selected;
    
    NSString *name = [[self.letterResultArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    
    NSString *ID = [[name componentsSeparatedByString:@"\\"] lastObject];
    
    NSDictionary *dict = [self.dataDict objectForKey:ID];
    
    VenueVipModel *venueVipModel = [VenueVipModel mj_objectWithKeyValues:dict];
    
    if (cell.selectBtn.selected) {
        
        [self.selectArray addObject:venueVipModel];
    }
    else{
        
        [self.selectArray removeObject:venueVipModel];
    }
}

#pragma mark - private
- (void)timerHandler:(NSTimer *)sender
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:.3 animations:^{
            self.sectionTitleView.alpha = 0;
        } completion:^(BOOL finished) {
            self.sectionTitleView.hidden = YES;
        }];
    });
}

-(void)showSectionTitle:(NSString*)title{
    
    [self.sectionTitleView setText:title];
    
    self.sectionTitleView.hidden = NO;
    
    self.sectionTitleView.alpha = 1;
    
    [self.timer invalidate];
    
    self.timer = nil;
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerHandler:) userInfo:nil repeats:NO];
    
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

#pragma mark 排序选择

-(void)sortBtnClick{
    
    selectStr = @"characterSort";
    
    [self.tableView reloadData];
}

-(void)sortRegBtnClick{
    
    selectStr = @"regSort";
    
    [self.tableView reloadData];
}

#pragma mark 添加VIP会员

/**
 添加VIP会员
 */
-(void)addVipMember{
    
    AddVenueVipViewController *addVenueVipVC = [[AddVenueVipViewController alloc] init];
    
    [self.navigationController pushViewController:addVenueVipVC animated:YES];
}

-(void)rightBtnClick{
    
    if (self.selectArray.count == 0) {
        
        [MBProgressHUD showText:@"请选择会员"];
        
        return;
    }
    
    if (self.sendSelectVipBlock) {
        
        NSString *vipIdStr = @"";
        for (VenueVipModel *venueVipModel in self.selectArray) {
            
            vipIdStr = [NSString stringWithFormat:@"%@%@,",vipIdStr,venueVipModel.MemberID];
        }
        
        vipIdStr = vipIdStr?[vipIdStr substringWithRange:NSMakeRange(0, vipIdStr.length - 1)]:@"";
        
        NSString *nameStr = [NSString stringWithFormat:@"%lu个会员",(unsigned long)self.selectArray.count];
        
        self.sendSelectVipBlock(vipIdStr, nameStr);
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark Get

-(UILabel *)sectionTitleView{
    
    if (!_sectionTitleView) {
        
        _sectionTitleView = [[UILabel alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-100)/2, (SCREEN_HEIGHT-100)/2,100,100)];
        _sectionTitleView.textAlignment = NSTextAlignmentCenter;
        _sectionTitleView.font = [UIFont boldSystemFontOfSize:60];
        _sectionTitleView.textColor = [UIColor blueColor];
        _sectionTitleView.backgroundColor = CSWhiteColor;
        _sectionTitleView.layer.cornerRadius = 6;
        _sectionTitleView.layer.borderWidth = 1.f/[UIScreen mainScreen].scale;
        _sectionTitleView.layer.borderColor = [UIColor groupTableViewBackgroundColor].CGColor;
        [self.view addSubview:_sectionTitleView];
        _sectionTitleView.hidden = YES;
    }
    
    return _sectionTitleView;
}

-(NSMutableArray *)dataArray{
    
    if (!_dataArray) {
        
        _dataArray = [[NSMutableArray alloc] init];
    }
    
    return _dataArray;
}

-(NSMutableDictionary *)dataDict{
    
    if (!_dataDict) {
        
        _dataDict = [[NSMutableDictionary alloc] init];
    }
    
    return _dataDict;
}

-(NSMutableArray *)stringsToSort{
    
    if (!_stringsToSort) {
        
        _stringsToSort = [[NSMutableArray alloc] init];
    }
    
    return _stringsToSort;
}

-(NSMutableArray *)selectArray{
    
    if (!_selectArray) {
        
        _selectArray = [[NSMutableArray alloc] init];
    }
    
    return _selectArray;
}

@end
